/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package di.persistence.dao.impl;

import di.persistence.dao.DIHibernateDaoSupport;
import di.persistence.dao.UserDao;
import di.persistence.dao.UserTypeDao;
import di.persistence.entities.User;
import di.persistence.entities.UserType;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Kilian Ito
 */
@Repository("UserDao")
public class UserDaoImpl extends DIHibernateDaoSupport implements UserDao {
 
    
    @Override
    public void save(User user) throws DataAccessException {
            getHibernateTemplate().save(user);
    }

    @Override
    public void update(User user) throws DataAccessException {
            getHibernateTemplate().update(user);
    }

    @Override
    public void delete(User user) throws DataAccessException {
            getHibernateTemplate().delete(user);
    }

    @Override
    public User getUser(long id) throws DataAccessException {
        return getHibernateTemplate().get(User.class, id);
    }

    @Override
    public User getUserByLogin(final String login) throws DataAccessException {
        return getHibernateTemplate().execute(new HibernateCallback<User>() {
            @Override
            public User doInHibernate(Session sn) throws HibernateException, SQLException {
                Criteria criteria = sn.createCriteria(User.class);
                criteria.add(Restrictions.ilike("login", login));
                criteria.setMaxResults(1);
                return (User)criteria.uniqueResult();
            }
        });
    }

    @Override
    public User getUserByEmail(final String email) throws DataAccessException {
        return getHibernateTemplate().execute(new HibernateCallback<User>() {
            @Override
            public User doInHibernate(Session sn) throws HibernateException, SQLException {
                Criteria criteria = sn.createCriteria(User.class);
                criteria.add(Restrictions.ilike("email", email));
                criteria.setMaxResults(1);
                return (User)criteria.uniqueResult();
            }
        });
    }
    
    @Override
    public List<UserType> getTypes(final User user) throws DataAccessException {
        if (user.getId() == null)
            return null;
        return getHibernateTemplate().get(User.class, user.getId()).getTypes();
    }
}
